package com.ruoyi.file.controller;

import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteFileInfoService;
import com.ruoyi.system.api.domain.JsjxFileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.file.service.ISysFileService;
import com.ruoyi.system.api.domain.SysFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;

/**
 * 文件请求处理
 *
 * @author ruoyi
 */
@RestController
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private RestTemplate restTemplate;

//    @Autowired
//    private RemoteFileInfoService remoteFileInfoService;

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<JsjxFileInfo> upload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();

            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            JsjxFileInfo jsjxFileInfo = new JsjxFileInfo();
            jsjxFileInfo.setFileId(IdUtils.simpleUUID());
            jsjxFileInfo.setFileName(sysFile.getName());
            jsjxFileInfo.setFileType(sysFile.getName().split("\\.")[1]);
            jsjxFileInfo.setFileUrl(url);
            jsjxFileInfo.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
            JsjxFileInfo fileInfo = restTemplate.postForObject("http://lingyu-jsjx/fileInfo/insert", jsjxFileInfo, JsjxFileInfo.class);
//            return remoteFileInfoService.insert(jsjxFileInfo);
            return R.ok(fileInfo);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 根据fileUrl下载文件
     */
    @GetMapping("download")
    public void download(@RequestParam("fileUrl") String fileUrl,
                         HttpServletRequest request,
                         HttpServletResponse response) {
        InputStream inputStream = null;
        try {
            // 获取项目根目录
            String basePath = System.getProperty("user.dir");
            // 构造实际文件路径，假设文件存储在upload目录下
            String realPath = basePath + "/uploadFile" + fileUrl.replace("/statics", ""); // 拼接完整路径

            // URL解码处理中文文件名
            realPath = URLDecoder.decode(realPath, "UTF-8");

            File file = new File(realPath);
            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("文件不存在");
                return;
            }

            String fileName = java.net.URLDecoder.decode(fileUrl.substring(fileUrl.lastIndexOf('/') + 1), "UTF-8");

            // 设置响应头，正确处理中文文件名
            response.setContentType("application/octet-stream");

            // 针对不同浏览器处理文件名编码
            String userAgent = request.getHeader("User-Agent");
            if (userAgent != null && userAgent.toLowerCase().contains("firefox")) {
                // Firefox浏览器使用Base64编码
                fileName = "=?UTF-8?B?" + java.util.Base64.getEncoder().encodeToString(fileName.getBytes("UTF-8")) + "?=";
            } else {
                // 其他浏览器使用URL编码
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                // 替换空格编码，避免某些浏览器问题
                fileName = fileName.replace("+", "%20");
            }

            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentLength((int) file.length());

            // 读取文件并写入响应流
            inputStream = new FileInputStream(file);
            OutputStream outputStream = response.getOutputStream();

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.flush();
        } catch (Exception e) {
            log.error("文件下载失败", e);
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("文件下载失败: " + e.getMessage());
            } catch (Exception ex) {
                log.error("响应写入失败", ex);
            }
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.error("关闭输入流失败", e);
                }
            }
        }
    }
}